package com.hzyl.famousreader.view.fragment;


import android.arch.lifecycle.Observer;
import android.arch.lifecycle.ViewModelProviders;
import android.content.Context;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.blankj.utilcode.util.BarUtils;
import com.blankj.utilcode.util.SPUtils;
import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.hzyl.famousreader.Constant;
import com.hzyl.famousreader.R;
import com.hzyl.famousreader.ThemeColor;
import com.hzyl.famousreader.repository.persistence.entity.Ad;
import com.hzyl.famousreader.repository.persistence.entity.Book;
import com.hzyl.famousreader.repository.webservice.cache.Resource;
import com.hzyl.famousreader.repository.webservice.model.BookWrapper;
import com.hzyl.famousreader.router.Router;
import com.hzyl.famousreader.view.adapter.ShopAdapter;
import com.hzyl.famousreader.viewmodel.AdViewModel;
import com.hzyl.famousreader.viewmodel.BookViewModel;
import com.hzyl.famousreader.databinding.*;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.listener.OnBannerListener;
import com.youth.banner.loader.ImageLoader;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * 书城
 */
@Route(path = "/main/shop")
public class ShopFragment extends BaseFragment {

  private FragmentShopBinding binding;

  private BookViewModel bookViewModel;

  private AdViewModel adViewModel;

  private List<Ad> ads = Collections.EMPTY_LIST;

  private Banner banner;

  @Override
  public View onCreateView(LayoutInflater inflater, ViewGroup container,
                           Bundle savedInstanceState) {

    super.onCreateView(inflater, container, savedInstanceState);

    binding = DataBindingUtil.inflate(inflater, R.layout.fragment_shop, container, false);

    int colorId = SPUtils.getInstance().getInt(Constant.SP_THEME_COLOR,  ThemeColor.DEFAULT.getColor());
    BarUtils.setStatusBarColor(getActivity(), colorId, 0);
    binding.toolbar.setBackgroundColor(colorId);

    bookViewModel = ViewModelProviders.of(this).get(BookViewModel.class);
    adViewModel = ViewModelProviders.of(this).get(AdViewModel.class);

    ShopAdapter shopAdapter = new ShopAdapter(null);
    shopAdapter.setOnItemClickListener((BaseQuickAdapter adapter, View view, int position) -> {
      List<BookWrapper> bookWrappers = adapter.getData();
      Book book = bookWrappers.get(position).getBooks().get(0);
      ARouter.getInstance().build("/book/info").withObject("book", book).navigation();
    });

    binding.shopRvDetail.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false));
    binding.shopRvDetail.setAdapter(shopAdapter);

    View header = getLayoutInflater().inflate(R.layout.fragment_shop_header, binding.shopRvDetail,false);
    shopAdapter.addHeaderView(header);




    //广告位
    banner = header.findViewById(R.id.banner);
    banner.setIndicatorGravity(BannerConfig.RIGHT);
    banner.isAutoPlay(true);
    banner.setDelayTime(2000);
    banner.setImageLoader(new GlideImageLoader());
    banner.setOnBannerListener(new OnBannerListener() {
      @Override
      public void OnBannerClick(int position) {
        if(ads != null && ads.size() > 0) {
          ARouter.getInstance().build(Router.ACTIVITY_WEB).withString("url", ads.get(position).getUrl()).navigation(getActivity());
        }
      }
    });

    adViewModel.adBanners().observe(this, new Observer<Resource<List<Ad>>>() {
      @Override
      public void onChanged(@Nullable Resource<List<Ad>> listResource) {
        List<Ad> list = listResource.data;
        if(list != null && list.size() > 0) {
          ads = list;
          List<String> imgUrls = new ArrayList<>();
          for(Ad ad : ads) {
            imgUrls.add(ad.getPath());
          }
          banner.setImages(imgUrls);
          banner.start();
          header.setVisibility(View.VISIBLE);
        } else {
          ads = Collections.EMPTY_LIST;
          banner.setImages(ads);
          banner.stopAutoPlay();
          header.setVisibility(View.GONE);
        }
      }
    });
    banner.start();

    //书籍推荐列表
    bookViewModel.recommendBooks().observe(this, new Observer<Resource<List<BookWrapper>>>() {
      @Override
      public void onChanged(@Nullable Resource<List<BookWrapper>> listResource) {
        if (listResource.data != null && listResource.data.size() > 0) {
          shopAdapter.setNewData(Collections.unmodifiableList(listResource.data));
          shopAdapter.notifyDataSetChanged();
        }
      }
    });

    return binding.getRoot();
  }


  @Override
  public void onResume() {
    super.onResume();
    banner.startAutoPlay();
  }

  @Override
  public void onDestroy() {
    super.onDestroy();
    banner.stopAutoPlay();
  }

  class GlideImageLoader extends ImageLoader {
    @Override
    public void displayImage(Context context, Object path, ImageView imageView) {
      Glide.with(context).load(String.valueOf(path)).into(imageView);
    }
  }

}
